@file:Suppress("MemberVisibilityCanBePrivate", "StaticFieldLeak")

package com.zjun.demo.experimentaldemo.utils

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager

/**
 * 需要先执行init初始化
 */
object PackageUtil {

    private lateinit var context: Context

    fun init(context: Context) {
        this.context = context.applicationContext
    }

    /**
     * 判断是否安装某个应用
     * android11以上需要在AndroidManifest manifest节点下添加所需的包名
     * ```xml
     * <queries>
     *    <package android:name="com.tencent.mobileqq" />
     * </queries>
     * ```
     * @param packageName 包名
     */
    fun isPackageInstalled(packageName: String, flags: Int = PackageManager.GET_ACTIVITIES): Boolean {
        val result: Boolean
        val packageInfo = getPackageInfo(packageName = packageName, flags = flags)
        result = packageInfo != null
        return result
    }

    /**
     * 检索系统上安装的应用程序包的总体信息
     * android11以上需要在AndroidManifest manifest节点下添加所需的包名
     * 例如
     * ```xml
     * <queries>
     *    <package android:name="com.tencent.mobileqq" />
     * </queries>
     * ```
     * @param packageName 包名
     */
    fun getPackageInfo(packageName: String, flags: Int = PackageManager.GET_ACTIVITIES): PackageInfo? {
        val packageInfo: PackageInfo?
        try {
            packageInfo = context.packageManager.getPackageInfo(packageName, flags)
            return packageInfo
        } catch (e: PackageManager.NameNotFoundException) {
            return null
        }
    }

}